package eu.inmite.harmony.lib.validations.form.validators;

import eu.inmite.harmony.lib.validations.form.annotations.AnnotationsHelper;
import eu.inmite.harmony.lib.validations.form.iface.IValidator;
import eu.inmite.harmony.lib.validations.util.LogUtil;

import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;
import java.lang.annotation.Annotation;

/**
 * @author Tomas Vondracek
 */
public abstract class BaseValidator<T> implements IValidator<T> {
    private static final String TAG = BaseValidator.class.getName();

    @Override
    public String getMessage(Context context, Annotation annotation, T input) {
        Object value = AnnotationsHelper.getAnnotationValue(annotation);
        Integer messageId = (Integer) AnnotationsHelper.getAnnotationValueWithName(annotation, "messageId");

        String message = null;
        if (messageId != null && messageId > 0) {
            try {
                message = context.getResourceManager().getElement(messageId).getString();
            } catch (IOException e) {
                LogUtil.error(TAG, "IOException " + e.toString());
            } catch (NotExistException e) {
                LogUtil.error(TAG, "NotExistException " + e.toString());
            } catch (WrongTypeException e) {
                LogUtil.error(TAG, "WrongTypeException " + e.toString());
            }
        }
        return message;
    }

    @Override
    public int getOrder(Annotation annotation) {
        Integer order = (Integer) AnnotationsHelper.getAnnotationValueWithName(annotation, "order");
        if (order != null) {
            return order;
        }
        return 0;
    }
}
